﻿using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml.Linq;

namespace Avivo
{
	public partial class ChartForm : Form
	{
		#region Private members
		private ChartView view = null;
		#endregion

		#region Constructor
		public ChartForm()
		{
			InitializeComponent();
			InitializeChart();
			LoadQuery();
		}
		#endregion

		#region Protected methods
		protected void InitializeChart()
		{
			view = new ChartView();
			view.Dock = DockStyle.Fill;
			container.Panel2.Controls.Add(view);
		}

		protected void LoadQuery()
		{
			try
			{
				var doc = XDocument.Load("query.xml");
				if (doc.Root.Name == "sqlchart")
				{
					//Restore SQL settings
					txtConnectionString.Text = doc.Root.Element("connection").Value;
					txtQuery.Text = doc.Root.Element("query").Value;

					//Restore window settings for better UX
					var window = doc.Root.Element("window");
					this.Width = int.Parse(window.Attribute("width").Value);
					this.Height = int.Parse(window.Attribute("height").Value);
					container.SplitterDistance = int.Parse(window.Attribute("split").Value);
					view.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), window.Attribute("chart").Value);
				}
			}
			catch
			{
			}
		}

		protected void SaveQuery()
		{
			try
			{
				var doc = new XDocument();
				doc.Add(new XElement("sqlchart"));
				doc.Root.Add(new XElement("window",
					new XAttribute("width", this.Width),
					new XAttribute("height", this.Height),
					new XAttribute("split", container.SplitterDistance),
					new XAttribute("chart", view.ChartType.ToString())
				));
				doc.Root.Add(new XElement("connection", txtConnectionString.Text));
				doc.Root.Add(new XElement("query", txtQuery.Text));
				doc.Save("query.xml");
			}
			catch
			{
			}
		}

		protected void RefreshSize()
		{
			txtConnectionString.Width = txtQuery.Width = container.SplitterDistance - 20;
			txtQuery.Height = container.Height - 120;
		}
		#endregion

		#region Event handlers
		private void container_SizeChanged(object sender, EventArgs e)
		{
			RefreshSize();
		}

		private void container_SplitterMoved(object sender, SplitterEventArgs e)
		{
			RefreshSize();
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			try
			{
				view.ConnectionString = txtConnectionString.Text;
				view.Query = txtQuery.Text;
				view.Generate();
				SaveQuery();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void ChartForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			try
			{
				SaveQuery();
			}
			catch
			{
			}
		}
		#endregion
	}
}
